import axios from "axios";

const service = axios.create({
  baseURL: "http://localhost:5560/",
  timeout: 60000,
});

// 接口打印处理函数
function log(
  bgColor,
  fontColor = "#fff",
  isSuccess,
  url = "",
  method,
  params,
  data
) {
  console.log("");
  console.log(
    "%c%s",
    `background:${bgColor}; font-size: 14px;color:${fontColor};`,
    "↓ ===================== ↓"
  );
  console.log(
    "%c%s",
    `background:${bgColor}; font-size: 14px;color:${fontColor};`,
    "响应状态：",
    isSuccess || "后台接口报错"
  );
  console.log(
    "%c%s",
    `background:${bgColor}; font-size: 14px;color:${fontColor};`,
    "请求地址：",
    url
  );
  console.log(
    "%c%s",
    `background:${bgColor}; font-size: 14px;color:${fontColor};`,
    "请求类型：",
    method || "post"
  );
  console.log(
    "%c%s",
    `background:${bgColor}; font-size: 14px;color:${fontColor};`,
    "请求参数：",
    params || "无参请求"
  );
  console.log(
    "%c%s",
    `background:${bgColor}; font-size: 14px;color:${fontColor};`,
    "响应数据：",
    data
  );
  console.log(
    "%c%s",
    `background:${bgColor}; font-size: 14px;color:${fontColor};`,
    "↑ ===================== ↑"
  );
  console.log("");
}
// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // 判断是否为h5还是pc
    const isMobile = !navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    // 在发送请求之前做些什么
    config.headers.Authorization =
      "Bearer " + window.localStorage.getItem("token");
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    if (response.data.status == 2000) {
      log(
        "green",
        "#fff",
        response.data.message || response.data.msg || "成功",
        response.request.responseURL,
        response.config.method,
        JSON.parse(response.config.data),
        response.data
      );
    } else {
      log(
        "red",
        "#000",
        response.data.message || response.data.msg || "非2000成功",
        response.request.responseURL,
        response.config.method,
        JSON.parse(response.config.data),
        response.data
      );
    }

    // 对响应数据做点什么
    return response.data;
  },
  function (error) {
    // 对响应错误做点什么
    let errMsg =
      "请求报错 状态码：" +
      error.response.status +
      "; code: " +
      error.code +
      "; 报错 msg: " +
      error.message;
    log(
      "red",
      "#000",
      errMsg,
      error.request.responseURL,
      error.config.method,
      JSON.parse(error.config.data),
      error.response.data
    );
    let data = error.response.data;
    return Promise.reject(data);
  }
);

export default service;
